package org.ns.longhttp.push;

import com.alibaba.fastjson.JSON;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.ns.longhttp.entity.DataEntry;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

public class PushClient implements AutoCloseable {

    public static void main(String[] args) throws Exception{
        PushClient pushClient = new PushClient();
        pushClient.push("http://localhost:11111/test", "test", "123456");
        pushClient.close();
    }

    CloseableHttpClient client;
    public PushClient() {
        HttpClientBuilder builder = HttpClientBuilder.create();
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(20000)
                .setConnectTimeout(20000)
                .setConnectionRequestTimeout(20000)
                .build();
        builder.setDefaultRequestConfig(requestConfig);
        client = builder.build();
    }

    public PushResult push(String url, String mtype, Object content) throws IOException {

        BasicHttpEntity entity = new BasicHttpEntity();
        DataEntry dataEntry = new DataEntry();
        dataEntry.setContent(content);
        dataEntry.setMtype(mtype);
        String dataJson = JSON.toJSONString(dataEntry);
        entity.setContent(new ByteArrayInputStream(dataJson.getBytes(Charset.forName("UTF-8"))));
        entity.setContentType("application/json;charset=UTF-8");
        HttpPost request = new HttpPost(url);
        request.setEntity(entity);
        try (CloseableHttpResponse httpResponse = client.execute(request)){
            StatusLine statusLine = httpResponse.getStatusLine();
            return new PushResult(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }
    }

    @Override
    public void close() {
        try {
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
